<?php
require_once('internal/IModule.interface.php');
require_once('modules/site/content/settings.php');
class Content {
	function __construct($engine=null) {
		$this->page = (empty($_GET['page']) || ($_GET['page']<1)) ? 1 : (int)$_GET['page'];
		$this->showedPosts = 5;
		$this->showedPages = 5;
		$this->engine = $engine;
	}
	function execute() {
		$this->showPages();
		$this->showPosts();
		$this->showPages();
	}
	function showPosts() {
		global $db, $mae;

		$offset = ($this->page-1)*$this->showedPosts;

		$db->modeAssoc();
		$q = $db->selectLimit("SELECT * FROM {$mae['db_prefix']}content ORDER BY posted DESC", $this->showedPosts, $offset);
		foreach($q as $k => $r) {
			?>
			<div class="post">
				<h3><div><span><?php echo $r['title']; ?></span></div></h3>
				<h5><div><span><?php echo $this->formatData($r); ?></span></div></h5>
				<p><?php echo $r['text']; ?></p>
			</div>
			<?php
		}
	}
	function showPages() {
		global $db;

		// Counting all posts
		$db->modeNum();
		$q = $db->select('content', 'COUNT(*)');
		$count = (int)$q->fields[0];

		// Counting pages
		$pages = ceil($count/$this->showedPosts);
		$start = ($this->page < $this->showedPages-1) ? 1 : $this->page;
		$start = ($start > $pages-$this->showedPages+1) ? $start : $pages-$this->showedPages+1;
		$end = $start+$this->showedPages;
		if ($end>($pages+1)) $end = $pages+1;

		// Displaying page counter
		?>
		<div class="pages">
			<?php echo "Page <b>{$this->page}</b> of <b>$pages</b>";?><br />
			<?php
			if ($pages > 1) {
				if ($this->page > 1) {
					echo '<a href="?page=1">&lt;&lt;</a> ';
					echo '<a href="?page='.($this->page-1).'">&lt;</a> ';
				}
				for ($i=$start; $i<$end; $i++) {
					if ($i==$this->page) echo $i.' ';
					else echo '<a href="?page='.$i.'">'.$i.'</a> ';
				}
				if ($this->page < $pages) {
					echo '<a href="?page='.($this->page+1).'">&gt;</a> ';
					echo '<a href="?page='.$pages.'">&gt;&gt;</a> ';
				}
			}
			?>
		</div>
		<?php
	}
	function formatData($r) {
		global $sets;

		// Every tag begins with an '%' sign
		$tags = array(
			'a' => '<span class="postauthor">'.$r['author'].'</span>', // Post author
			't' => '<span class="posttime">'.$r['posted'].'</span>'    // Posting time
		);
		reset($tags);

		$res = $sets['pattern'];
		while (list($key, $val) = each($tags)) $res = str_replace('%'.$key, $val, $res);
		return $res;
	}
}
?>
